import re
from user_agents import parse


def version_filter(string):
    """后缀版本过滤函数"""
    res = re.findall(r"(.*?) \d.*[a-z0-9A-Z]{0,10}", string)
    if res:
        return res[0]
    return "Other"


def ua_parser(user_agent):
    """UA 解析函数"""
    ua = parse(user_agent)

    device = ua.get_device()
    raw_browser = ua.get_browser()
    raw_system = ua.get_os()

    browser = version_filter(raw_browser)
    system = version_filter(raw_system)

    data = {
        "browser": browser,
        "system": system,
        "raw_browser": raw_browser,
        "raw_system": raw_system,
        "device": device,
    }

    return data


if __name__ == '__main__':

    ua_list = [
        "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/92.0.4515.107 Safari/537.36",
        "Mozilla/5.0 (Linux; Android 9; 16s Build/PKQ1.190202.001; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/89.0.4389.72 MQQBrowser/6.2 TBS/045814 Mobile Safari/537.36 V1_AND_SQ_8.8.33_2150_YYB_D A_8083300 QQ/8.8.33.6300 NetType/WIFI WebP/0.3.0 Pixel/1080 StatusBarHeight/85 SimpleUISwitch/0 QQTheme/1000 InMagicWin/0 StudyMode/0 CurrentMode/0 CurrentFontScale/1.0",
        "Mozilla/5.0",
        "Mozilla/5.0 (Linux; U; Android 4.0; en-us; GT-I9300 Build/IMM76D) AppleWebKit/534.30 (KHTML, like Gecko) Version/4.0 Mobile Safari/534.30",
        "Mozilla/5.0 (iPhone; CPU iPhone OS 13_2_3 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/13.0.3 Mobile/15E148 Safari/604.1",
    ]

    for item in ua_list:
        print(ua_parser(item))
